import Vue from 'vue'
import App from './App'
import store from './store'
import router from './router/index'

Vue.config.productionTip = false

/* eslint-disable no-new */

new Vue({
  el: '#root',
  components: { App },
	template:'<App/>',
	store,
	router,
  methods:{
    // 发送消息 toId 目标Channel id
    sending:function(content,toId){
      if(content == ""){
        return ;
      }
      if(toId == ""){
        return ;
			}
			console.log(content,toId)
      var createTime = new Date().getTime();
			var msg = "{\"from\": \""+username+"\",\"groupId\":\""+groupId+"\",\"to\": \""+toId+"\",\"cmd\":11,\"createTime\":"+createTime+",\"msgType\": \"0\",\"content\": \""+content+"\"}";
			console.log(msg)
      socket.send(msg);
		},
		getUsers:function(){
			socket.send("{\"cmd\":17,\"type\":\"2\"}","abc")
		},
		closeChat:function(){
			socket.send("{\"cmd\":14}")
		}
  },
  created(){
    connect()
  }

})
// 定义一个全局过滤器
Vue.filter('time',(date)=>{
	if (date === ''){
		 return '';
	 }
   if (typeof date === 'string') {
       date = new Date(date);
   }
   if(date.getMinutes()<10){
     return date.getMonth() + '-' + date.getDay() + ' ' + date.getHours() + ':0' +date.getMinutes();
   }else{
     return date.getMonth() + '-' + date.getDay() + ' ' + date.getHours() + ':' + date.getMinutes();
   }
});

// socket连接
var socket ;
var logDiv;
var username;
var onSelected;
var onlineUserCmd = "{\"cmd\":17,\"type\":\"1\"}";
var curUser;
var onlineUserArray = [];
var groupId;
//创建连接
function connect(){
	if(curUser){
		alert("当前已登录,请先退出登录!");
		return;
	}
	var ip = "192.168.5.206";
	var port = 5678;
	username = getUrlParam("user");
	var password = "pass";
	logDiv = document.getElementById('logs');
	socket = new WebSocket("ws:"+ip+":"+port+"?username="+username+"&password="+password);
	socket.onopen = function(e){
		heartCheck.start()
    store.state.online="已连接"// vuex state更新
		var userCmd = "{\"cmd\":17,\"type\":\"1\",\"userid\":\""+username+"\"}";
		socket.send(userCmd);//获取登录用户信息;
	};
	socket.onerror = function(e){
		conosole.log("error:"+e)
	};
	socket.onclose = function(e){
    curUser = null;
    store.state.online="未连接"// vuex state更新
		console.log("exit")
	};
	socket.onmessage = function(e){
		heartCheck.reset()
    var data = e.data;
		var dataObj = eval("("+data+")");//转换为json对象
		console.log(dataObj,dataObj.code)
	   if("undefined" == typeof(dataObj.code) && dataObj.command == "COMMAND_CHAT_RESP"){//接收到聊天响应处理;
		   COMMAND_CHAT_RESP(dataObj);
	   }else if(dataObj.code = 100 && dataObj.command == "COMMAND_GET_USER_RESP"){//获取用户信息响应处理;
		   COMMAND_GET_USER_RESP(dataObj);
	   }else if(0 == dataObj.code && dataObj.command == "COMMAND_CHAT_RESP"){//聊天发送状态;
		   COMMAND_CHAT_RESP_SEND_STATUS(data);
	   }else if("400" == dataObj.code && dataObj.command == "COMMAND_JOIN_GROUP_RESP"){//加入群组响应状态处理;
		   COMMAND_JOIN_GROUP_RESP(dataObj);
	   }else if(dataObj.command == "COMMAND_JOIN_GROUP_NOTIFY_RESP"){//加入群组的消息通知处理;
		   COMMAND_JOIN_GROUP_NOTIFY_RESP(dataObj);
	   }else if(dataObj.command == "COMMAND_EXIT_GROUP_NOTIFY_RESP"){
		   COMMAND_EXIT_GROUP_NOTIFY_RESP(dataObj);
		 }else if(dataObj.command== "COMMAND_HEARTBEAT_REQ"){

		 }
		 else{
		   OTHER(data);
	   }
	};
}
function COMMAND_HEARTBEAT_REQ_NOTIFY(data){
	console.log("心跳检测:"+data.data)
}
function COMMAND_EXIT_GROUP_NOTIFY_RESP(data){
	var exitGroupNotify = eval("("+data.data+")");
	//logDiv.innerHTML+="<font color='#A3A3A3' size='1'>"+exitGroupNotify.user.nick+"("+exitGroupNotify.user.id+")退出群聊...</font><br>";
	//socket.send(onlineUserCmd);//获取在线用户列表;
}
//加入群组的消息通知处理;
function COMMAND_JOIN_GROUP_NOTIFY_RESP(data){
	var joinGroupNotify = eval("("+data.data+")");
	//logDiv.innerHTML+="<font color='#A3A3A3' size='1'>"+joinGroupNotify.user.nick+"("+joinGroupNotify.user.id+")加入群聊...</font><br>";
	//socket.send(onlineUserCmd);//获取在线用户列表;
}
//加入群组响应状态处理;
function COMMAND_JOIN_GROUP_RESP(data){
	  //成功加入群组响应信息;
}
//发送聊天请求发送状态处理;
function COMMAND_CHAT_RESP_SEND_STATUS(data){
     //发送成功后的状态处理...
}
//获取用户信息响应处理;
function COMMAND_GET_USER_RESP(data){
		var onlineUsers = eval("("+data.data+")");
		console.log(onlineUsers)
		if(!Array.isArray(onlineUsers)){
			curUser = onlineUsers;
		}else{
			onlineUserArray = [];
			for(var i = 0 ; i < onlineUsers.length ; i++){
				onlineUserArray.push(onlineUsers[i]);
			}
		}
		let tempUserArray=[]
		onlineUserArray.forEach(function (v){
			if(v.id!=username){
				tempUserArray.unshift({
					id:v.id,
					name:v.nick,
					groupId:v.groups.groupId
				})
			}
		})
		console.log(tempUserArray)
		store.commit("APPEND_ONLINE_SERVICES",tempUserArray)
}
//接收到聊天响应处理;
function COMMAND_CHAT_RESP(data){
		var chatObj = data.data
		// if(chatObj.from == username)
		// 	console.log("SAME USER")
		//   return;
		let obj={
			toId:chatObj.to,
			msg:chatObj.content,
			fromId:chatObj.from,
		}
		console.log(data)
		store.commit("APPEND_CHAT_MESSAGE",obj)
}
function OTHER(data){
	console.log("其他信息:"+data)
}

//心跳机制
var heartCheck={
	timeout:50000,
	timeoutObj:null,
	reset:function(){
		clearTimeout(this.timeoutObj);
		this.start();
	},
	start:function(){
		this.timeoutObj = setTimeout(function(){
			socket.send("{'cmd':13,'hbbyte':'1'}");
		},this.timeout)
	}
}

function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = window.location.search.substr(1).match(reg);  //匹配目标参数
	if (r != null) return unescape(r[2]); return null; //返回参数值
}